<template>
  <view class="vip-container">
    <!-- 会员信息 -->
    <view class="vip-header" :class="{'is-vip': userInfo.vip > 0}">
      <view class="user-info">
        <view class="avatar-box">
          <u-avatar :src="userInfo.avatar" size="160rpx"></u-avatar>
        </view>
        <view class="info-box">
          <view class="nickname">{{ userInfo.nickname || userInfo.username }}</view>
          <view class="vip-level" v-if="userInfo.vip > 0">
            <u-icon name="level" color="#FFD700" size="32"></u-icon>
            <text>VIP{{ userInfo.vip }}</text>
          </view>
          <view class="vip-expire" v-if="userInfo.vip > 0">
            有效期至：{{ vipExpireDate }}
          </view>
          <view class="no-vip" v-else>
            您还不是会员，开通会员享受更多权益
          </view>
        </view>
      </view>
    </view>
    
    <!-- 会员权益 -->
    <view class="vip-benefits">
      <view class="section-title">会员权益</view>
      <view class="benefits-grid">
        <view class="benefit-item" v-for="(item, index) in benefitsList" :key="index">
          <view class="benefit-icon">
            <u-icon :name="item.icon" size="60" color="#f9ae3d"></u-icon>
          </view>
          <view class="benefit-name">{{ item.name }}</view>
        </view>
      </view>
    </view>
    
    <!-- 会员套餐 -->
    <view class="vip-packages">
      <view class="section-title">会员套餐</view>
      <view class="packages-list">
        <view 
          class="package-item" 
          v-for="(item, index) in packagesList" 
          :key="index"
          :class="{'active': selectedPackage === index}"
          @click="selectPackage(index)"
        >
          <view class="package-name">{{ item.name }}</view>
          <view class="package-price">
            <text class="price-symbol">¥</text>
            <text class="price-value">{{ item.price }}</text>
          </view>
          <view class="package-original" v-if="item.original">原价：¥{{ item.original }}</view>
          <view class="package-desc">{{ item.desc }}</view>
          <view class="package-tag" v-if="item.tag">{{ item.tag }}</view>
        </view>
      </view>
    </view>
    
    <!-- 支付方式 -->
    <view class="payment-methods">
      <view class="section-title">支付方式</view>
      <view class="methods-list">
        <view 
          class="method-item" 
          v-for="(item, index) in paymentMethods" 
          :key="index"
          :class="{'active': selectedPayment === index}"
          @click="selectPayment(index)"
        >
          <view class="method-icon">
            <u-icon :name="item.icon" size="40" :color="item.color"></u-icon>
          </view>
          <view class="method-name">{{ item.name }}</view>
          <view class="method-check">
            <u-icon name="checkmark-circle" size="40" color="#3c9cff" v-if="selectedPayment === index"></u-icon>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 支付按钮 -->
    <view class="payment-action">
      <u-button type="primary" @click="handlePayment">
        立即支付 ¥{{ packagesList[selectedPackage].price }}
      </u-button>
    </view>
    
    <!-- 会员协议 -->
    <view class="vip-agreement">
      <u-checkbox v-model="agreeProtocol" shape="circle" size="30"></u-checkbox>
      <text class="agreement-text">我已阅读并同意</text>
      <text class="agreement-link" @click="showProtocol">《会员服务协议》</text>
    </view>
    
    <!-- 协议弹窗 -->
    <u-popup v-model="showProtocolPopup" mode="center" border-radius="16" width="80%">
      <view class="protocol-popup">
        <view class="protocol-header">
          <view class="protocol-title">会员服务协议</view>
          <view class="protocol-close" @click="showProtocolPopup = false">
            <u-icon name="close" size="30"></u-icon>
          </view>
        </view>
        <scroll-view class="protocol-content" scroll-y>
          <view class="protocol-text">
            <view class="protocol-section">一、服务内容</view>
            <view class="protocol-paragraph">
              1.1 本服务协议适用于您使用本应用提供的会员服务，本应用向您提供包括但不限于专属内容、资源下载、广告屏蔽等特权服务。
            </view>
            <view class="protocol-paragraph">
              1.2 您在使用会员服务前应当仔细阅读本协议，确认同意本协议全部条款后方可开通会员服务。
            </view>
            
            <view class="protocol-section">二、会员费用</view>
            <view class="protocol-paragraph">
              2.1 会员服务为付费服务，您可以选择不同的会员套餐进行购买。
            </view>
            <view class="protocol-paragraph">
              2.2 会员服务一经购买成功，除法律法规明确规定外，不支持退款。
            </view>
            
            <view class="protocol-section">三、会员权益</view>
            <view class="protocol-paragraph">
              3.1 会员权益以实际页面展示为准，本应用有权根据业务发展调整会员权益内容。
            </view>
            <view class="protocol-paragraph">
              3.2 会员权益仅限会员本人使用，不得转让、出售或与他人共享，否则本应用有权终止您的会员资格。
            </view>
            
            <view class="protocol-section">四、协议修改</view>
            <view class="protocol-paragraph">
              4.1 本应用有权根据业务发展需要修改本协议，修改后的协议将在应用内公布。
            </view>
            <view class="protocol-paragraph">
              4.2 如您不同意修改后的协议，可以选择不继续使用会员服务；如您继续使用会员服务，则视为您接受修改后的协议。
            </view>
          </view>
        </scroll-view>
        <view class="protocol-footer">
          <u-button type="primary" @click="agreeAndCloseProtocol">同意并关闭</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { user } from '@/api/cms'

export default {
  data() {
    return {
      userInfo: {
        username: '',
        nickname: '',
        avatar: '',
        vip: 0,
        vip_expiretime: ''
      },
      benefitsList: [
        { icon: 'download', name: '资源下载' },
        { icon: 'eye-off', name: '广告屏蔽' },
        { icon: 'star', name: '专属内容' },
        { icon: 'server-man', name: '优先客服' },
        { icon: 'tags', name: '专属标识' },
        { icon: 'coupon', name: '优惠券' }
      ],
      packagesList: [
        { name: '月度会员', price: 18, original: 30, desc: '有效期30天', tag: '' },
        { name: '季度会员', price: 48, original: 90, desc: '有效期90天', tag: '超值' },
        { name: '年度会员', price: 168, original: 360, desc: '有效期365天', tag: '最划算' }
      ],
      paymentMethods: [
        { name: '微信支付', icon: 'weixin-circle', color: '#09BB07' },
        { name: '支付宝', icon: 'zhifubao-circle', color: '#1677FF' },
        { name: '余额支付', icon: 'rmb-circle', color: '#f56c6c' }
      ],
      selectedPackage: 1, // 默认选中季度会员
      selectedPayment: 0, // 默认选中微信支付
      agreeProtocol: false, // 是否同意协议
      showProtocolPopup: false // 是否显示协议弹窗
    }
  },
  computed: {
    // 会员到期日期
    vipExpireDate() {
      if (!this.userInfo.vip_expiretime) return '未知'
      
      const date = new Date(this.userInfo.vip_expiretime * 1000)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    }
  },
  onLoad() {
    this.getUserInfo()
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        const { data } = await user.getUserInfo()
        if (data.code === 1) {
          this.userInfo = data.data.userInfo
        } else {
          uni.showToast({
            title: data.msg || '获取用户信息失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取用户信息失败', error)
        uni.showToast({
          title: '获取用户信息失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 选择套餐
    selectPackage(index) {
      this.selectedPackage = index
    },
    
    // 选择支付方式
    selectPayment(index) {
      this.selectedPayment = index
    },
    
    // 显示协议
    showProtocol() {
      this.showProtocolPopup = true
    },
    
    // 同意协议并关闭弹窗
    agreeAndCloseProtocol() {
      this.agreeProtocol = true
      this.showProtocolPopup = false
    },
    
    // 处理支付
    handlePayment() {
      if (!this.agreeProtocol) {
        uni.showToast({
          title: '请先同意会员服务协议',
          icon: 'none'
        })
        return
      }
      
      const packageInfo = this.packagesList[this.selectedPackage]
      const paymentInfo = this.paymentMethods[this.selectedPayment]
      
      // 构建支付参数
      const params = {
        package_id: this.selectedPackage,
        package_name: packageInfo.name,
        price: packageInfo.price,
        payment_type: this.selectedPayment
      }
      
      // 调用支付接口
      this.createOrder(params)
    },
    
    // 创建订单
    async createOrder(params) {
      try {
        uni.showLoading({
          title: '正在创建订单'
        })
        
        const { data } = await user.createVipOrder(params)
        
        uni.hideLoading()
        
        if (data.code === 1) {
          // 根据支付方式调用不同的支付接口
          if (this.selectedPayment === 0) {
            // 微信支付
            this.wxPay(data.data)
          } else if (this.selectedPayment === 1) {
            // 支付宝支付
            this.aliPay(data.data)
          } else if (this.selectedPayment === 2) {
            // 余额支付
            this.balancePay(data.data)
          }
        } else {
          uni.showToast({
            title: data.msg || '创建订单失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('创建订单失败', error)
        uni.showToast({
          title: '创建订单失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 微信支付
    wxPay(orderInfo) {
      // 模拟支付成功
      setTimeout(() => {
        this.paySuccess()
      }, 1000)
    },
    
    // 支付宝支付
    aliPay(orderInfo) {
      // 模拟支付成功
      setTimeout(() => {
        this.paySuccess()
      }, 1000)
    },
    
    // 余额支付
    async balancePay(orderInfo) {
      try {
        uni.showLoading({
          title: '支付中'
        })
        
        const { data } = await user.balancePay({
          order_id: orderInfo.order_id
        })
        
        uni.hideLoading()
        
        if (data.code === 1) {
          this.paySuccess()
        } else {
          uni.showToast({
            title: data.msg || '支付失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('余额支付失败', error)
        uni.showToast({
          title: '支付失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 支付成功
    paySuccess() {
      uni.showToast({
        title: '支付成功',
        icon: 'success'
      })
      
      // 更新用户信息
      this.getUserInfo()
      
      // 跳转到支付成功页面
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages_mine/pages/vip/success'
        })
      }, 1500)
    }
  }
}
</script>

<style lang="scss" scoped>
.vip-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 30rpx;
}

.vip-header {
  background-color: #3c9cff;
  padding: 40rpx 30rpx;
  color: #ffffff;
  
  &.is-vip {
    background: linear-gradient(135deg, #3c9cff, #5c6bc0);
  }
  
  .user-info {
    display: flex;
    align-items: center;
    
    .avatar-box {
      margin-right: 30rpx;
    }
    
    .info-box {
      flex: 1;
      
      .nickname {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }
      
      .vip-level {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;
        
        text {
          margin-left: 10rpx;
          font-size: 28rpx;
          color: #FFD700;
        }
      }
      
      .vip-expire, .no-vip {
        font-size: 24rpx;
        opacity: 0.8;
      }
    }
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  padding: 30rpx 30rpx 20rpx;
}

.vip-benefits {
  background-color: #ffffff;
  margin-bottom: 20rpx;
  
  .benefits-grid {
    display: flex;
    flex-wrap: wrap;
    padding: 0 15rpx 30rpx;
    
    .benefit-item {
      width: 33.33%;
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 30rpx;
      
      .benefit-icon {
        margin-bottom: 10rpx;
      }
      
      .benefit-name {
        font-size: 28rpx;
        color: #666666;
      }
    }
  }
}

.vip-packages {
  background-color: #ffffff;
  margin-bottom: 20rpx;
  
  .packages-list {
    display: flex;
    padding: 0 20rpx 30rpx;
    
    .package-item {
      flex: 1;
      margin: 0 10rpx;
      border: 2rpx solid #e5e5e5;
      border-radius: 12rpx;
      padding: 20rpx;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;
      
      &.active {
        border-color: #3c9cff;
        box-shadow: 0 4rpx 16rpx rgba(60, 156, 255, 0.2);
      }
      
      .package-name {
        font-size: 28rpx;
        font-weight: bold;
        color: #333333;
        text-align: center;
        margin-bottom: 10rpx;
      }
      
      .package-price {
        text-align: center;
        margin-bottom: 10rpx;
        
        .price-symbol {
          font-size: 24rpx;
          color: #f56c6c;
          vertical-align: top;
        }
        
        .price-value {
          font-size: 40rpx;
          font-weight: bold;
          color: #f56c6c;
        }
      }
      
      .package-original {
        font-size: 24rpx;
        color: #999999;
        text-decoration: line-through;
        text-align: center;
        margin-bottom: 10rpx;
      }
      
      .package-desc {
        font-size: 24rpx;
        color: #666666;
        text-align: center;
      }
      
      .package-tag {
        position: absolute;
        top: 0;
        right: 0;
        background-color: #f56c6c;
        color: #ffffff;
        font-size: 20rpx;
        padding: 4rpx 16rpx;
        transform: rotate(45deg) translate(20rpx, -10rpx);
        width: 120rpx;
        text-align: center;
      }
    }
  }
}

.payment-methods {
  background-color: #ffffff;
  margin-bottom: 20rpx;
  
  .methods-list {
    padding: 0 30rpx 30rpx;
    
    .method-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      &.active {
        background-color: #f9f9f9;
      }
      
      .method-icon {
        margin-right: 20rpx;
      }
      
      .method-name {
        flex: 1;
        font-size: 28rpx;
        color: #333333;
      }
    }
  }
}

.payment-action {
  padding: 0 30rpx;
  margin-bottom: 20rpx;
}

.vip-agreement {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 30rpx;
  
  .agreement-text {
    font-size: 24rpx;
    color: #666666;
    margin-left: 10rpx;
  }
  
  .agreement-link {
    font-size: 24rpx;
    color: #3c9cff;
  }
}

.protocol-popup {
  display: flex;
  flex-direction: column;
  max-height: 80vh;
  
  .protocol-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid #f5f5f5;
    
    .protocol-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
    }
  }
  
  .protocol-content {
    flex: 1;
    padding: 30rpx;
    max-height: 60vh;
    
    .protocol-section {
      font-size: 30rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 20rpx;
      margin-top: 30rpx;
      
      &:first-child {
        margin-top: 0;
      }
    }
    
    .protocol-paragraph {
      font-size: 28rpx;
      color: #666666;
      line-height: 1.6;
      margin-bottom: 16rpx;
    }
  }
  
  .protocol-footer {
    padding: 20rpx 30rpx 30rpx;
    border-top: 1px solid #f5f5f5;
  }
}
</style>